import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_demo/components/Input.dart';
import 'package:flutter_demo/components/Toast.dart';
import 'package:flutter_demo/components/header.dart';
import 'package:flutter_demo/router/router.dart';
import 'package:flutter_demo/service/login.dart';
import 'package:flutter_demo/service/request.dart';
import 'package:flutter_demo/utils/LocalStorage.dart';
import 'package:device_info/device_info.dart';

// main
class PhoneLogin extends StatefulWidget {
  PhoneLogin({Key key}) : super(key: key);

  @override
  _PhoneLoginState createState() => _PhoneLoginState();
}

class _PhoneLoginState extends State<PhoneLogin> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Material(
        child: Container(
          decoration: BoxDecoration(color: Color.fromRGBO(26, 26, 26, 1)),
          child: Stack(alignment: Alignment.center, children: [
            Header(),
            Positioned(
                top: MediaQuery.of(context).size.height * 2 / 5,
                child: LoginInfo())
          ]),
        ),
      ),
    );
  }
}

// username psw verticalfy
class LoginInfo extends StatefulWidget {
  @override
  _LoginInfoState createState() => _LoginInfoState();
}

class _LoginInfoState extends State<LoginInfo> {
  String phone = '';
  String verticalfy = '';
  Map boolMap = {
    'disable': true, // 判断是否进行倒计时
  };
  bool shouldCountDown = false;
  DeviceInfoPlugin deviceInfo;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getDeviceInfo();
  }

  getDeviceInfo() async {
    deviceInfo = DeviceInfoPlugin();
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    print(
        'imei：${androidInfo.id}  androidId：${androidInfo.androidId}'); // e.g. "Moto G (4)"

    // IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
    // print('Running on ${iosInfo.utsname.machine}'); // e.g. "iPod7,1"
  }

  @override
  Widget build(BuildContext context) {
    // 判断按钮当前状态
    judgeLoginBtnStatus() {
      RegExp exp = RegExp(
          r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
      if (exp.hasMatch(this.phone) && this.verticalfy.length == 6) {
        setState(() {
          this.boolMap['disable'] = false;
        });
      } else {
        setState(() {
          this.boolMap['disable'] = true;
        });
      }
    }

    return Column(
      children: [
        Container(
          width: 280,
          child: Input(onChange: (e) {
            setState(() {
              this.phone = e;
            });
            judgeLoginBtnStatus();
          }),
        ),
        SizedBox(
          height: 14,
        ),
        Container(
          child: Row(
            children: [
              Container(
                width: 184,
                child: Input(
                  placeholder: '验证码',
                  maxLength: 6,
                  onChange: (e) {
                    setState(() {
                      this.verticalfy = e;
                    });
                    judgeLoginBtnStatus();
                  },
                ),
              ),
              SizedBox(
                width: 14,
              ),
              Container(
                decoration: BoxDecoration(
                    color: Color(0xFF844AFF),
                    borderRadius: BorderRadius.circular(22)),
                width: 80,
                height: 45,
                child: InkWell(
                  onTap: () {
                    if (shouldCountDown) return;
                    RegExp exp = RegExp(
                        r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
                    if (exp.hasMatch(this.phone)) {
                      phoneLogin(
                        context,
                        {
                          'phone': this.phone,
                        },
                        HttpMethod.Post,
                      ).then((res) {
                        if (res['code'] == 200) {
                          Toast.toast(context, msg: '验证码发送成功');
                          setState(() {
                            this.shouldCountDown = true;
                          });
                        }
                      });
                    } else {
                      Toast.toast(
                        context,
                        msg: '请输入正确的手机号',
                      );
                    }
                  },
                  child: GetVerticalFyBtn(shouldCountDown, success: () {
                    setState(() {
                      shouldCountDown = false;
                    });
                  }),
                ),
              ),
            ],
          ),
        ),
        SizedBox(
          height: 20,
        ),
        InkWell(
          onTap: () {
            phoneLogin(context, {'phone': this.phone, 'code': this.verticalfy},
                    HttpMethod.Post)
                .then((res) {
              print(res);
              if (res['code'] == 200) {
                // LocalStorage.set('user', res['data']['data']['user']);
                RouterConfig.navigater(
                  context,
                  path: '/index',
                  type: 'redirect',
                );
              }
            });
          },
          child: LoginBtn(
            disable: boolMap['disable'],
          ),
        ),
        SizedBox(
          height: 24,
        ),
        Text(
          '未注册账号登录后自动注册',
          style: TextStyle(color: Color(0xFF777777), fontSize: 12),
        )
      ],
    );
  }
}

// 登录按钮
class LoginBtn extends StatelessWidget {
  LoginBtn({this.disable = true});
  final bool disable;
// 不可点击按钮
  final Widget disableBtn = Container(
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(28),
      border: Border.all(color: Color(0xFF844AFF), width: 1),
    ),
    width: 56,
    height: 56,
    child: Center(
      child: Text(
        '登录',
        style: TextStyle(color: Color(0xFF777777), fontSize: 14),
      ),
    ),
  );

  // 可点击按钮
  final Widget ableBtn = Container(
    decoration: BoxDecoration(
        color: Color(0xFF844AFF), borderRadius: BorderRadius.circular(56)),
    width: 56,
    height: 56,
    child: Center(
      child: Text(
        '登录',
        style: TextStyle(color: Colors.white, fontSize: 14),
      ),
    ),
  );
  @override
  Widget build(BuildContext context) {
    if (this.disable) {
      return Container(child: disableBtn);
    } else {
      return Container(child: ableBtn);
    }
  }
}

//  获取验证码按钮
class GetVerticalFyBtn extends StatefulWidget {
  GetVerticalFyBtn(this.shouldCountdown, {this.success});
  final bool shouldCountdown;
  final Function success;
  @override
  _GetVerticalFyBtnState createState() => _GetVerticalFyBtnState();
}

class _GetVerticalFyBtnState extends State<GetVerticalFyBtn> {
  _GetVerticalFyBtnState();
  int residue = 60;
  String countTime = '60 s';
  Timer countDownTimer;
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    countDownTimer.cancel();
    countDownTimer = null;
  }

  @override
  Widget build(BuildContext context) {
    countDownTime() {
      countDownTimer?.cancel(); //如果已存在先取消置空
      countDownTimer = null;
      setState(() {
        countTime = '$residue s';
      });
      countDownTimer = new Timer.periodic(new Duration(seconds: 1), (t) {
        setState(() {
          if (residue > 0) {
            //60-t.tick代表剩余秒数，如果大于0
            countTime = "${residue - t.tick} s";
            residue -= t.tick;
          } else {
            countDownTimer.cancel();
            countDownTimer = null;
            residue = 60;
            countTime = '$residue s';
          }
        });
        if (residue < 1) {
          widget.success();
        }
      });
    }

    if (!widget.shouldCountdown) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            '获取',
            style: TextStyle(color: Colors.white, fontSize: 12),
          ),
          Text(
            '验证码',
            style: TextStyle(color: Colors.white, fontSize: 12),
          )
        ],
      );
    } else {
      countDownTime();
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            countTime,
            style: TextStyle(color: Colors.white, fontSize: 12),
          ),
        ],
      );
    }
  }
}
